<?php

namespace App\Http\Controllers\Internal\User;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\AppletAuth;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Service\Cruise\Check\CruiseCheckCompanyService;
use App\Service\Cruise\Check\CruiseCheckSpecialService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class UserController extends BaseController
{
    /**
     * @throws ValidationException
     */
    public function getChatGroupIdByUser(Request $request): JsonResponse
    {
        $this->validate($request, [
            'shopId' => 'integer|min:1',
            'userId' => 'integer|min:1',
        ]);

        $shopId = $request->get('shopId', 0);
        $userId = $request->get('userId', 0);

        $group = ChatGroupUserModel::checkAppUserIn($shopId, $userId, ChatGroupModel::TYPE_CUSTOMER_SERVE);

        return $this->success([
            'groupId' => (int)optional($group)->id
        ]);
    }

    public function fsMiniTokenAuth(Request $request): JsonResponse
    {
        (new AppletAuth())->handle($request, function (){});

        return $this->success(['user' => $request->userInfo]);
    }

    /**
     * 判断用户是否属于三方服务
     * @throws ValidationException
     */
    public function checkCruiseCheckUser(Request $request): JsonResponse
    {
        $this->validate($request, [
            'userId' => 'required|int|gt:0',
        ], [
            'userId.required' => '用户ID必填',
            'userId.gt'       => '无效用户ID',
        ]);

        $userId  = (int)$request->get('userId');

        $exist = FsCompanyUserModel::query()
            ->where('rmsUserId', $userId)
            ->exists();

        if (!$exist) {
            return $this->success(['exist' => false]);
        }

        // 判断该用户下是否存在正常的供应商
        $haveFsCompanyIds = CruiseCheckSpecialService::getNormalFsCompanyIds($userId);

        if (!count($haveFsCompanyIds)) {
            return $this->success(['exist' => false]);
        }

        return $this->success(['exist' => true]);
    }
}
